//
//  ActiveView.m
//  lv678
//
//  Created by apple on 15/6/17.
//  Copyright (c) 2015年 lampshade. All rights reserved.
//

#import "ActiveView.h"
#import "AFNetworking.h"

@implementation ActiveView


// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
    //设置textfield代理
    _memberCard.delegate      = self;
    _systemPsw.delegate       = self;
    _phoneNum.delegate        = self;
    _identityCode.delegate    = self;
    _reallyName.delegate      = self;
    _newsPsw.delegate         = self;
    _confirmPsw.delegate      = self;
    _emailAddress.delegate    = self;

    NSString *path            = [[NSBundle mainBundle]pathForResource:@"UrlList" ofType:@"plist"];
    NSMutableDictionary *data = [[NSMutableDictionary alloc]initWithContentsOfFile:path];
    url                       = [data valueForKey:@"memberCenter"];
    
    
}

//点击空白处关闭软键盘
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    [self endEditing:YES];
}

//开始编辑输入框的时候，软键盘出现，执行此事件
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    CGRect frame                     = textField.frame;
    int offset                       = frame.origin.y + 70 - (self.frame.size.height - 216.0);//键盘高度216

    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ActiveView" context:nil];
    [UIView setAnimationDuration:animationDuration];

    //将视图的Y坐标向上移动offset个单位，以使下面腾出地方用于软键盘的显示
    if(offset > 0)
    self.frame                       = CGRectMake(0.0f, -offset, self.frame.size.width, self.frame.size.height);

    [UIView commitAnimations];
}

//当用户按下return键或者按回车键，keyboard消失
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

//输入框编辑完成以后，将视图恢复到原始状态
-(void)textFieldDidEndEditing:(UITextField *)textField
{
    self.frame =CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
}
//点击激活按钮验证并提交数据
- (IBAction)activeBtn:(id)sender {
    //检查卡号是否存在以及存在是否激活
    AFHTTPRequestOperationManager *manager            = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer                        = [AFJSONResponseSerializer serializer];
    manager.requestSerializer                         = [AFJSONRequestSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
    NSDictionary *isExistCode                         = @{@"serviceName":@"isExistCode",@"queryParameters":@{@"vipcode":_memberCard.text}};
    [manager POST:url parameters:isExistCode success:^(AFHTTPRequestOperation *operation, id responseObject) {
        status = [[responseObject objectForKey:@"status"]intValue];
        comment = [responseObject valueForKey:@"comment"];
        if (status == 0) {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:comment delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
            _memberCard.text   = nil;
            [_memberCard becomeFirstResponder];
        }else{
            //初始密码不能为空
            if ([_systemPsw.text isEqualToString:@""]) {
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"初始密码不能为空" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alert show];
                _systemPsw.text    = nil;
                [_systemPsw becomeFirstResponder];
            }else{
                //检查初始密码是否正确
                NSDictionary *checkInitialPassword = @{@"serviceName":@"checkInitialPassword",@"queryParameters":@{@"vipcode":_memberCard.text,@"password":_systemPsw.text}};
                [manager POST:url parameters:checkInitialPassword success:^(AFHTTPRequestOperation *operation, id responseObject) {
                status = [[responseObject objectForKey:@"status"]intValue];
                comment = [responseObject valueForKey:@"comment"];
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:comment delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                    [alert show];
                _systemPsw.text = nil;
                    [_systemPsw becomeFirstResponder];
                } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                    
                }];
                //手机号不能为空
                if ([_phoneNum.text isEqualToString:@""]) {
                    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"手机号不能为空" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                    [alert show];
                    _phoneNum.text     = nil;
                    [_phoneNum becomeFirstResponder];
                }else{
                    //手机号是否存在
                    NSDictionary *isExistTelephone = @{@"serviceName":@"checkInitialPassword",@"queryParameters":@{@"telephone":_phoneNum.text}};
                    [manager POST:url parameters:isExistTelephone success:^(AFHTTPRequestOperation *operation, id responseObject) {
                    status = [[responseObject objectForKey:@"status"]intValue];
                    comment                        = [responseObject valueForKey:@"comment"];
                        if (status == 0) {
                    UIAlertView *alert             = [[UIAlertView alloc]initWithTitle:nil message:comment delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                            [alert show];
                    _phoneNum.text                 = nil;
                            [_phoneNum becomeFirstResponder];
                        }
                    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                    }];
                    //验证码是否为空
                    if ([_identityCode.text isEqualToString:@""]) {
                        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"验证码不能为空" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                        [alert show];
                        _identityCode.text = nil;
                        [_identityCode becomeFirstResponder];
                    }else{
                        //验证验证码是否正确
                        NSDictionary *sendSms = @{@"serviceName":@"sendSms",@"queryParameters":@{@"telephone":_phoneNum.text}};
                        [manager POST:url parameters:sendSms success:^(AFHTTPRequestOperation *operation, id responseObject) {
                        status = [[responseObject objectForKey:@"status"]intValue];
                        NSArray *value        = [responseObject valueForKey:@"dataList"];
                        NSString *random      = [value valueForKey:@"randomCode"];
                            if (![_identityCode.text isEqualToString:random]) {
                        UIAlertView *alert    = [[UIAlertView alloc]initWithTitle:nil message:@"验证码不正确" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                                [alert show];
                        _identityCode.text    = nil;
                                [_identityCode becomeFirstResponder];
                            }
                        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                        }];
                        if (self.recommendTelephone.text != nil || self.recommendTelephone.text != NULL) {
                            NSDictionary *data = @{@"serviceName":@"checkRecommendTelephone",@"queryParameters":
                                                       @{@"RecommendTelephone":self.recommendTelephone.text}};
                            [manager POST:url parameters:data success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
                                int sta = [[responseObject valueForKey:@"status"]intValue];
                                if (sta == 0) {
                                    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"推荐手机号不存在" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                                    [alert show];
                                }else{
                                    
                                }
                            } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
                                NSLog(@"erroe%@",error);
                            }];
                        }
                       
                    }
                }
            }
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (_memberCard == textField) {
        if (range.location>10) {
            return NO;
        }
    }
    if (_systemPsw == textField) {
        if (range.location>5) {
            return NO;
        }
    }
    if (_phoneNum == textField) {
        if (range.location>10) {
            return NO;
        }
    }
    if (_identityCode == textField) {
        if (range.location>5) {
            return NO;
        }
    }
    if (_identityCard == textField) {
        if (range.location>18) {
            return NO;
        }
    }
    return YES;
}
//点击获取验证码按钮进行倒计时（GCD）
- (IBAction)getIdentityCode:(id)sender {
    __block int time = 10;
    dispatch_queue_t queue   = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);//每秒执行
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0*NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timer, ^{
        if (time==0) {// 当为0时关闭倒计时提示
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                [_identityBtn setTitle:@"重新发送" forState:UIControlStateNormal];
                [_identityBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
                
                _identityBtn.userInteractionEnabled = YES;
            });
            
        }else{
            //            int minutes = timeout / 60;
            int seconds       = time % 60;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [_identityBtn setTitle:[NSString stringWithFormat:@"%@秒后重新发送",strTime] forState:UIControlStateNormal];
                [_identityBtn setTitleColor:[UIColor brownColor] forState:UIControlStateNormal];
                _identityBtn.userInteractionEnabled = NO;
                
                
                
                
            });
            time--;
            
        }
        
    });
    dispatch_resume(_timer);
}
@end
